<template>
  <el-container class="exchange">
    <el-main>
      <el-card shadow="never" class="tableCard">
        <vxe-toolbar :refresh="{query: getList1}" >
          <template v-slot:buttons>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTree"
          border
          row-key
          resizable
          highlight-hover-row
          :auto-resize="true"
          :data="list"
          width
          max-height="500"
          row-id="id"
          highlight-current-row
          text-algin="center"
          :print-config="{}"
          header-align="center" >
          <vxe-table-column field="name"  width="180" align="center"  title="服务端" />
          <vxe-table-column show-overflow title="备注" field="remark" align="left"  min-width="250" />
          <vxe-table-column show-overflow title="状态"  field="publishStatus"  align="left"  width="100" >
           <template slot-scope="scope">
             <el-switch v-model="scope.row.publishStatus" :inactive-value="0" :active-value="1" active-text inactive-text @change="changPublishState(scope)" />
           </template>
          </vxe-table-column>
          <vxe-table-column  title="操作" fixed="right" align="center" width="100" >
            <template slot-scope="scope">
              <div class="drag-btn">
                <el-button
                  type="text"
                  size="mini"
                  @click="openDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="openTemplateListDialog(scope.row)"
                >模板</el-button>
              </div>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-card>
      <el-dialog width="40%" :close-on-click-modal="false" :modal="false" :visible.sync="dialogVisible" title="信息编辑">
        <el-form ref="ruleForm" :model="params" label-width="7rem" :rules="rules">
          <el-row :gutter="40">
            <el-col :span="23">
              <el-form-item label="服务名称：" prop="name">
                <el-input v-model="params.name" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="23">
              <el-form-item label="备注：" prop="remark">
                <el-input v-model="params.remark" type="textarea" :rows="2"  :disabled="configEditDisable"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button v-if="!configEditDisable" type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog   width="45%" title="系统消息模板" :visible.sync="dialogTemplateFormVisible" :close-on-click-modal="false" :modal="false">
          <vxe-toolbar :refresh="{query: getTemplateList1}" >
          </vxe-toolbar>
            <vxe-table
              ref="xTree"
              border
              row-key
              resizable
              highlight-hover-row
              :auto-resize="true"
              :data="templateList"
              width
              max-height="500"
              row-id="id"
              highlight-current-row
              text-algin="center"
              :print-config="{}"
              header-align="center"
              show-overflow
            >
              <vxe-table-column
                field="templateCode"
                width="180"
                align="center"
                title="模板代码"
              />
              <vxe-table-column
                field="templateName"
                min-width="220"
                align="center"
                title="模板名称"
              />
              <vxe-table-column
                field="name"
                width="80"
                align="center"
                title="状态">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.publishStatus"
                    :inactive-value="0"
                    :active-value="1"
                    active-text
                    inactive-text
                    @change="changeTemplateState(scope)"
                  />
                </template>
              </vxe-table-column>
              <vxe-table-column
                title="操作"
                fixed="right"
                align="center"
                min-width="100"
              >
                <template slot-scope="scope">
                  <div class="drag-btn">
                    <el-button
                      type="text"
                      size="mini"
                      @click="openTemplateDialog(scope.row)"
                    >设置</el-button>
                  </div>
                </template>
              </vxe-table-column>
            </vxe-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogTemplateFormVisible = false">关 闭</el-button>
          </div>
      </el-dialog>
      <el-dialog width="45%" :close-on-click-modal="false" :visible.sync="dialogTemplateEditVisible" title="模板编辑">
        <el-form :model="templateParams" ref="ruleTemplateForm" label-width="6rem" :rules="templateRules">
          <el-row :gutter="40">
            <el-col :span="12">
            <el-form-item label="模板代码：" prop="templateCode">
                <el-input v-model="templateParams.templateCode" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板名称：" prop="templateName">
                <el-input v-model="templateParams.templateName" :disabled="true"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="消息标题：" prop="templateSubject">
                <el-input v-model="templateParams.templateSubject" :disabled="templateEditDisabled"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="模板内容：" prop="templateContent">
                <el-input id="templateContent" v-model="templateParams.templateContent" type="textarea" :rows="6" :disabled="templateEditDisabled"/>
                   <div style="height: 100px;line-height: 20px;">
                    <el-menu  @select="insertTemplateParam" :collapse="true" active-text-color="#000" v-if="!templateEditDisabled">
                      <el-submenu>
                        <template slot="title"> <i class="el-icon-document"></i> </template>
                        <el-menu-item
                            v-for="item in templateParamList"
                            :key="item.templateParam"
                            :index="item.templateParam"
                        >{{item.templateParamDesc}}</el-menu-item>
                      </el-submenu>
                    </el-menu>
                 </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTemplateEditVisible = false">取 消</el-button>
          <el-button v-if="!templateEditDisabled" type="primary" @click="submitTemplate">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import {
  listSysMsgConfig,viewSysMsgConfig,modifySysMsgConfig,changeSysMsgConfigStatus,listSysMsgTemplateParam,
  listSysMsgTemplateByConfigId,viewSysMsgTemplate,modifySysMsgTemplate,changeSysMsgTemplateStatus
} from '@/api/messageSetting'
import { searchAllDictionaries } from '@/api/public'

export default {
  components: {
  },
  data() {
    return {
      title: '',
      dialogVisible: false,
      configEditDisable: false,
      templateEditDisabled: false,
      dialogTemplateFormVisible: false,
      dialogTemplateEditVisible: false,
      params: {
        id:'',
        name:'',
        remark:''
      },
      templateParams: {
        id: '',
        configId: '',
        templateName:'',
        templateCode:'',
        templateContent:'',
        remark: ''
      },
      rules:{

      },
      templateRules: {
        templateName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        templateContent: [{ required: true, message: '请输入模板内容', trigger: 'blur' }],
        templateCode: [{ required: true, message: '模板代码', trigger: 'blur' }]
      },
      list: [],
      templateList: [],
      templateParamList: [],
      templateFlag:true,
      flag:true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList1(){
      this.getList()
    },
    // 列表
    getList() {
      listSysMsgConfig({}).then(res =>{
        if(res){
          if(res.code){
            this.$message.error(`${res.msg}`);
          }else{
            this.list = res
          }
        }
      })
    },
    openTemplateListDialog(row){
       this.dialogTemplateFormVisible = true
       this.templateParams.configId = row.id
       this.getTemplateList()
    },
    getTemplateList1(){
       this.getTemplateList()
    },
    getTemplateList() {
      if(this.templateParams.configId){
        listSysMsgTemplateByConfigId(this.templateParams.configId).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.templateList = res
            }
          }
        })
      }else{
        this.templateParams = {}
        this.dialogTemplateFormVisible = true
      }
    },
    getTemplateParamList() {
      if(this.templateParams.id){
        listSysMsgTemplateParam(this.templateParams.id).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.templateParamList = res
            }
          }
        })
      }else{
        this.templateParamList =[]
      }
    },
    insertTemplateParam(key) {
       let elInput = document.getElementById('templateContent')
       let startPos = elInput.selectionStart

       let endPos = elInput.selectionEnd

       if (startPos === undefined || endPos === undefined) {
           elInput.value= key
       } else {
           let txt = elInput.value
           let result = txt.substring(0, startPos) + key + txt.substring(endPos)
           elInput.value= result
       }
       elInput.$nextTick(() => {
           elInput.focus()
           elInput.selectionStart = startPos + key.length
           elInput.selectionEnd = startPos + key.length
       })

    },
    openTemplateDialog(row) {
      this.dialogTemplateEditVisible = true
      this.templateEditDisabled = row.publishStatus === 1?true:false
      if(row.id){
        this.templateFlag = true
        viewSysMsgTemplate(row.id).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.templateParams = res
              this.getTemplateParamList()
            }
          }
        })
      }else{
        this.templateFlag = false
        this.templateParams.templateCode = ''
        this.templateParams.templateName = ''
        this.templateParams.templateContent = ''
        this.templateParams.remark = ''
      }
    },

    // 新增 编辑
    openDialog(row) {
      this.dialogVisible = true
      this.configEditDisable = row.publishStatus === 1 ? true : false
      if(row.id){
        this.flag = true
        viewSysMsgConfig(row.id).then(res =>{
          if(res){
            if(res.code){
              this.$message.error(`${res.msg}`);
            }else{
              this.params = res
            }
          }
        })
      }else{
        this.flag = false
        Object.keys(this.params).forEach(key => this.params[key] = '')
      }
    },
    changPublishState(scope){
        this.list[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
        changeSysMsgConfigStatus({
          id: scope.row.id,
          status: scope.row.publishStatus === 1 ? 0 : 1
        }).then((response) => {
          this.list[scope.seq - 1].publishStatus = scope.row.publishStatus === 1 ? 0 : 1
          this.configEditDisable = scope.row.publishStatus === 1 ? true : false
          this.$message.success( scope.row.publishStatus === 0 ? '禁用成功' : '启用成功' )
          this.getList()
        })
    },
    changeTemplateState(scope){
      changeSysMsgTemplateStatus({id:scope.row.id, status:scope.row.publishStatus}).then(res =>{
        if (res) {
          this.$message.success('修改成功!')
          this.getTemplateList()
        } else {
          this.$message.error('修改失败!')
          this.getTemplateList()
        }
      })
    },
    // 保存
    submitTemplate(){
       this.$refs.ruleTemplateForm.validate((valid) => {
        if (valid) {
          if(this.templateFlag){
            modifySysMsgTemplate(this.templateParams).then(res=>{
              if(res){
                if(res.code){
                  this.$message.error(`${res.msg}`)
                }else{
                  this.$message.success('修改成功!')
                  this.getTemplateList()
                  this.dialogTemplateEditVisible = false
                }
              }
            })
          }
        }
       })
    },
    // 保存
    submit(){
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if(this.flag){
            modifySysMsgConfig(this.params).then(res=>{
              if(res){
                if(res.code){
                  this.$message.error(`${res.msg}`);
                }else{
                  this.$message.success('保存成功!')
                  this.getList()
                  this.dialogVisible = false
                }
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style>
  .el-menu .el-menu--vertical{
    border: none;
  }
 .el-menu .el-menu-item{
    background-color: #fff!important;

  }
  .el-menu .el-menu-item:hover{
    background-color: #fff!important;
  }
  .el-menu .el-submenu__title{
    background-color: #fff!important;
  }
  .el-menu .el-submenu__title:hover{
    background-color: #fff!important;
  }
  .el-menu--vertical .el-menu--popup .el-menu-item{
    min-height: 35px;
    line-height: 30px;
  }
  .el-menu--collapse .el-menu .el-submenu, .el-menu--popup {
     min-width: 150px;
  }
</style>
